package com.whately.core.base.fileupload.qiniu.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class VideoUtil {

    private final static Logger log = LoggerFactory.getLogger(VideoUtil.class);

    //视频测试
    public static void main(String[] args) {
        String filePath = "/Users/qinchao/Documents/xuexi/EBB4AC78FB92E7A2A4D6AC416540BAB7.mp4";
       // convertToH264(filePath);
    }

    /*

    public static boolean isMp4FormatAndH264(String filePath){
        boolean flag =false;
        FFmpegFrameGrabber frameGrabber = null;
        try{
            long t1 = System.currentTimeMillis();
            System.out.println("截取视频截图开始："+t1);
            // 第一帧图片存储位置
            String targerFilePath = filePath.substring(0, filePath.lastIndexOf("/"));
            // 视频文件名
            String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
            // 图片名称
            String targetFileName = fileName.substring(0, fileName.lastIndexOf("."));
            System.out.println("视频路径是：" + targerFilePath);
            System.out.println("视频文件名：" + fileName);
            System.out.println("图片名称是：" + targetFileName);

            frameGrabber = FFmpegFrameGrabber.createDefault(filePath);
            frameGrabber.start();
            //System.out.println("视频的容器格式：" + frameGrabber.getFormat());
            //System.out.println("视频的编码格式：" + frameGrabber.getVideoCodec());//avcodec.AV_CODEC_ID_H264 = 28 ;AV_CODEC_ID_MPEG4 = 13;
            if(avcodec.AV_CODEC_ID_H264==frameGrabber.getVideoCodec() && frameGrabber.getFormat().contains("mp4")){
                flag = true;
            }
            frameGrabber.stop();
            long t2 =System.currentTimeMillis();
            System.out.println("截取视频截图结束："+ t2);
            System.out.println("截取视频截图用时："+ (t2-t1)+"毫秒");
        } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
            log.error("VideoUtil getFormat error",e);
        } finally {
            if (frameGrabber != null) {
                try {
                    frameGrabber.stop();
                } catch (org.bytedeco.javacv.FrameGrabber.Exception e) {
                    log.error("VideoUtil getFormat stop frameGrabber error",e);
                }
            }
        }
        return flag;
    }

    public static String convertToH264(String filePath){
        FFmpegFrameGrabber frameGrabber = null;
        FFmpegFrameRecorder recorder = null;

        String fileName = null;

        try {
            fileName = filePath.replace(".mp4", "_edited.mp4");

            frameGrabber = new FFmpegFrameGrabber(filePath);
            frameGrabber.start();

            //已经是264编码了
            if(avcodec.AV_CODEC_ID_H264==frameGrabber.getVideoCodec() && frameGrabber.getFormat().contains("mp4")){
                return filePath;
            }

            recorder = new FFmpegFrameRecorder(fileName, frameGrabber.getImageWidth(), frameGrabber.getImageHeight(),frameGrabber.getAudioChannels());
            recorder.setVideoCodec(avcodec.AV_CODEC_ID_H264); //avcodec.AV_CODEC_ID_H264  //AV_CODEC_ID_MPEG4
            recorder.setFormat("mp4");
            recorder.setFrameRate(frameGrabber.getFrameRate());
            recorder.setSampleRate(frameGrabber.getSampleRate());

            //去掉这一句，否则报错：Could not open audio codec
            //recorder.setSampleFormat(frameGrabber.getSampleFormat());


            //-----recorder.setAudioChannels(frameGrabber.getAudioChannels());
            recorder.setFrameRate(frameGrabber.getFrameRate());
            recorder.start();

            while (true) {
                try {
                    Frame captured_frame = frameGrabber.grabFrame();

                    if (captured_frame == null) {
                        System.out.println("!!! Failed cvQueryFrame");
                        break;

                    }
                    recorder.setTimestamp(frameGrabber.getTimestamp());
                    recorder.record(captured_frame);

                } catch (Exception e) {
                    log.error("convertToH264 error",e);
                }
            }

        } catch (Exception e) {
            log.error("",e);
        }finally {
            if (recorder != null) {
                try {
                    recorder.stop();
                    recorder.release();
                } catch (Exception e) {
                    log.error("VideoUtil  stop recorder error",e);
                }
            }

            if (frameGrabber != null) {
                try {
                    frameGrabber.stop();
                } catch (Exception e) {
                    log.error("VideoUtil  stop frameGrabber error",e);
                }
            }
        }
        return fileName;
    }


*/



    /**
     * @Description: 获取视频截图
     */
    /*public static Map<String, Object> getScreenshot(String filePath) throws Exception{
        // 第一帧图片存储位置
        String targerFilePath = filePath.substring(0, filePath.lastIndexOf("/"));
        // 视频文件名
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        // 图片名称
        String targetFileName = fileName.substring(0, fileName.lastIndexOf("."));
        System.out.println("视频路径是：" + targerFilePath);
        System.out.println("视频文件名：" + fileName);
        System.out.println("图片名称是：" + targetFileName);

        System.out.println("截取视频截图开始："+ System.currentTimeMillis());
        Map<String, Object> result = new HashMap<String, Object>();
        FFmpegFrameGrabber grabber = FFmpegFrameGrabber.createDefault(filePath);

        grabber.start();
        //设置视频截取帧（默认取第一帧）
        org.bytedeco.javacv.Frame frame = grabber.grabImage();
        //视频旋转度
        String rotate = grabber.getVideoMetadata("rotate");
        Java2DFrameConverter converter = new Java2DFrameConverter();
        //绘制图片
        BufferedImage bi = converter.getBufferedImage(frame);
        if (rotate != null) {
            // 旋转图片
            bi = rotate(bi, Integer.parseInt(rotate));
        }
        //图片的类型
        String imageMat = "jpg";
        //图片的完整路径
        String imagePath = targerFilePath + File.separator + targetFileName + "." + imageMat;
        //创建文件
        File output = new File(imagePath);
        ImageIO.write(bi, imageMat, output);

        //拼接Map信息
        result.put("videoWide", bi.getWidth());
        result.put("videoHigh", bi.getHeight());
        long duration = grabber.getLengthInTime() / (1000 * 1000);
        result.put("rotate", StringUtils.isBlank(rotate)? "0" : rotate);
        result.put("format", grabber.getFormat());
        result.put("imgPath", output.getPath());
        System.out.println("视频的宽:" + bi.getWidth());
        System.out.println("视频的高:" + bi.getHeight());
        System.out.println("视频的旋转度：" + rotate);
        System.out.println("视频的格式：" + grabber.getFormat());
        System.out.println("此视频时长（s/秒）：" + duration);
        grabber.stop();
        System.out.println("截取视频截图结束："+ System.currentTimeMillis());
        return result;
    }*/

    /**
     * @Description: 根据视频旋转度来调整图片
     * @param src
     * @param angel	视频旋转度
     * @return  BufferedImage
     */
    /*public static BufferedImage rotate(BufferedImage src, int angel) {
        int src_width = src.getWidth(null);
        int src_height = src.getHeight(null);
        int type = src.getColorModel().getTransparency();
        Rectangle rect_des = calcRotatedSize(new Rectangle(new Dimension(src_width, src_height)), angel);
        BufferedImage bi = new BufferedImage(rect_des.width, rect_des.height, type);
        Graphics2D g2 = bi.createGraphics();
        g2.translate((rect_des.width - src_width) / 2, (rect_des.height - src_height) / 2);
        g2.rotate(Math.toRadians(angel), src_width / 2, src_height / 2);
        g2.drawImage(src, 0, 0, null);
        g2.dispose();
        return bi;
    }*/


    /**
     * @Description: 计算图片旋转大小
     * @param src
     * @param angel
     * @return  Rectangle
     */
    /*public static Rectangle calcRotatedSize(Rectangle src, int angel) {
        if (angel >= 90) {
            if (angel / 90 % 2 == 1) {
                int temp = src.height;
                src.height = src.width;
                src.width = temp;
            }
            angel = angel % 90;
        }
        double r = Math.sqrt(src.height * src.height + src.width * src.width) / 2;
        double len = 2 * Math.sin(Math.toRadians(angel) / 2) * r;
        double angel_alpha = (Math.PI - Math.toRadians(angel)) / 2;
        double angel_dalta_width = Math.atan((double) src.height / src.width);
        double angel_dalta_height = Math.atan((double) src.width / src.height);
        int len_dalta_width = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_width));
        int len_dalta_height = (int) (len * Math.cos(Math.PI - angel_alpha - angel_dalta_height));
        int des_width = src.width + len_dalta_width * 2;
        int des_height = src.height + len_dalta_height * 2;
        return new java.awt.Rectangle(new Dimension(des_width, des_height));
    }*/
}
